package kamikaze.service.product;

import java.util.Date;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;

import kamikaze.entity.Feedback;
import kamikaze.entity.Product;
import kamikaze.support.HttpMethod;
import kamikaze.support.Service;
import kamikaze.support.ServiceConfig;
import kamikaze.support.ServiceContext;
import kamikaze.support.ServiceException;
import kamikaze.support.StringUtil;

@ServiceConfig(path = "product.saverating.action", method = HttpMethod.POST)
public class SaveProductRatingService implements Service {

	@Override
	public String serve(ServiceContext ctx) throws Exception {
		
		ctx.getUserSession().ensureLoginAsUser();
		
		HttpServletRequest req = ctx.getRequest();
		
		final String id = req.getParameter("id");
		if (id != null && !id.isEmpty()) {

			String strRating = req.getParameter("prodRating");
			String strComment = req.getParameter("buyerComment");
			
			Integer rating = 1;
			if (strRating==null || strRating.isEmpty()) {
				throw new ServiceException("Please select the Rating");
			}else {
				rating = Integer.parseInt(strRating);
				if (rating<1 || rating>5) {
					throw new ServiceException("Invalid Rating");
				}
			}
			
			if (strComment==null || strComment.isEmpty()) {
				throw new ServiceException("Please provide the feedback");
			}else {
				strComment = StringUtil.sanitize(strComment);
			}
			
			
			Feedback feedback = new Feedback();
			feedback.setCommentorId(ctx.getUserSession().asUser().getId());
			feedback.setCommentorName(ctx.getUserSession().asUser().getName());
			feedback.setCreatedDate(new Date());
			feedback.setProductId(Long.valueOf(id));
			feedback.setRating(rating);
			feedback.setComment(strComment);
			
			ctx.getEntityManager().persist(feedback);
			
			Query q = ctx.getEntityManager().createQuery(
					"Select p from Product p where p.productId= :productId and deleted=false");
			q.setParameter("productId", Long.valueOf(id));
			Product product = (Product) q.getSingleResult();
			product.setRating(product.getRating()+rating/2);
			ctx.getEntityManager().persist(product);
			
			return "redirect:/service/product/detail?id="+id;

		} else {
			throw new ServiceException("Product ID is unknown.");
		}
		
	}
}
